package com.logos.tool;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;


/**
 * Created by llx on 2019/4/12
 * 此类辅助设置View的长按时长，自定义长按时长
 */
public class ViewLongClickUtil {

    private static final String TAG = "ViewLongClickUtil";

    /**
     * **
     * @param handler 外部handler
     * @param view view
     * @param delayMillis delayMillis
     * @param listener listener
     */
    public static void setLongClick(final Handler handler,
                                    final View view,
                                    final long delayMillis,
                                    final View.OnLongClickListener listener) {

        view.setOnTouchListener(new View.OnTouchListener() {
            private int mTouchMax = 50;
            private int mLastMotionX;
            private int mLastMotionY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                int x = (int) event.getX();
                int y = (int) event.getY();

                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_UP:
                        handler.removeCallbacks(mRunnable);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (Math.abs(mLastMotionX - x) > mTouchMax
                                || Math.abs(mLastMotionY - y) > mTouchMax) {
                            handler.removeCallbacks(mRunnable);
                        }
                        break;
                    case MotionEvent.ACTION_DOWN:
                        handler.removeCallbacks(mRunnable);
                        mLastMotionX = x;
                        mLastMotionY = y;
                        handler.postDelayed(mRunnable, delayMillis);
                        break;
                    default:
                        break;
                }
                return true;
            }

            private Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    if (listener != null) {
                        listener.onLongClick(view);
                    }
                }
            };
        });

    }

}
